﻿using SQLServer.DBUtility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using Tenancy.Helper;

namespace Tenancy.Server
{
    /// <summary>
    /// Hbung_Login 的摘要说明
    /// </summary>
    public class Hbung_Login : IHttpHandler
    {
        /// <summary>
        /// 登录成功返回用户信息 
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //用户登录的手机号
            string Hbung_Tel = context.Request.Params["Tel"];
            string Hbung_Phone = string.Empty;
            if (string.IsNullOrEmpty(Hbung_Tel))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("Tel为空"));
            }
            else
            {
                string pattern = "^1[0-9]{10}$"; //正则表达式字符串
                Regex cgsregex = new Regex(pattern);
                Hbung_Phone = DESEncrypt.MD5Decrypt(Hbung_Tel);
                bool isMatch = cgsregex.IsMatch(Hbung_Phone);
                if (!isMatch)
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("Tel格式不正确"));
                    return;
                }
            }
            //签名
            string HBsign = context.Request.Params["Sign"];
            if (string.IsNullOrEmpty(HBsign))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("Sign为空"));
                return;
            }
            else
            {
                if (GenerClass.IsOkMatch(Hbung_Phone) != Regex.Replace(HBsign, @"\s", "+"))
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("Sign不匹配"));
                    return;
                }
            }
            //方法名字 0 1
            string Hbung_Meth = context.Request.Params["Meth"];
            if (string.IsNullOrEmpty(Hbung_Meth))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("Meth为空"));
                return;
            }
            else
            {
                if (Hbung_Meth != "0" && Hbung_Meth != "1"&&Hbung_Meth != "2")
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("Meth格式不正确"));
                    return;
                }
            }
            //验证码
            string Hbung_CodeNum = context.Request.Params["CodeNum"];
            //获取验证码
            if (Hbung_Meth == "0")
            {
                if (GenerClass.TelISNORepeat(Hbung_Phone))
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("Tel尚未注册"));
                    return;
                }
                //随机生成六位数
                string SixNum = GenerClass.CreateNum();
                string VilateStr = string.Format("insert into Hbung_ValidateCode  (vCode,vTel,vType,vTime,Status) values ('{0}','{1}',3,getdate(),'1') ", SixNum, Hbung_Phone);
                if (DBHelpSQL.ExecuteSql(VilateStr) > 0)
                {
                    string msgcgs = "[{\"CodeNum\": \"" + SixNum + "\" }]";
                    context.Response.Write(GenerClass.SetSucessJsData("发送成功", msgcgs));
                    //此处发送验证码到手机
                    string Strmsg = "【利星行机械】登录验证码：" + SixNum + "感谢你的登录。";
                    Tenancy.Helper.MsgSend.HB_SendMsg(Hbung_Phone, Strmsg);
                }
                else
                {
                    context.Response.Write(GenerClass.SetChangeErrorJsData("获取验证码失败"));
                    return;
                }
            }
            //登录
            if(Hbung_Meth == "1")
            {
                if (string.IsNullOrEmpty(Hbung_CodeNum))
                {
                    context.Response.Write(GenerClass.SetChangeErrorJsData("CodeNum为空"));
                    return;
                }
                else
                {
                    string HB_ValiCode = string.Format("select * from Hbung_ValidateCode where vCode='{0}' and vTel='{1}' and vType='3' and Status='1' ", Hbung_CodeNum, Hbung_Phone);
                    DataTable HB_CodeDate = DBHelpSQL.Query(HB_ValiCode).Tables[0];
                    if (HB_CodeDate != null && HB_CodeDate.Rows.Count > 0)
                    {
                        string HB_InStr = string.Format("select * from Hbung_CompanyInfo where CellTel='{0}'", Hbung_Phone);
                        DataTable HB_ComInfo = DBHelpSQL.Query(HB_InStr).Tables[0];
                        if (HB_ComInfo != null && HB_ComInfo.Rows.Count>0)
                        {
                            string comna = string.Empty;//公司名字
                            string compho = string.Empty;//公司电话
                            string comaddress = string.Empty;//公司地址
                            string comspeo = string.Empty;//服务人员
                            string ZCData = string.Format(" select CTel,SID,SName,SSex,SMobile,CAddress,CName from View_CustomerForSaleman  where RegisterMobilephone='{0}'", Hbung_Phone);
                            DataTable Zcda = DbLocalSQL.Query(ZCData).Tables[0];
                            if (Zcda != null && Zcda.Rows.Count > 0)
                            {
                                comna = Zcda.Rows[0]["CName"].ToString();
                                compho = Zcda.Rows[0]["CTel"].ToString();
                                comaddress = Zcda.Rows[0]["CAddress"].ToString();
                                comspeo = Zcda.Rows[0]["SName"].ToString();
                                string WENStr = string.Format(@"update Hbung_CompanyInfo set CompanyName='{0}',Phone='{1}',Address='{2}',ServicePerson='{3}' where CellTel='{4}' ",
                                    comna, compho, comaddress, comspeo, Hbung_Phone
                                    );
                                DBHelpSQL.ExecuteSql(WENStr);
                            }

                            string MJStr= string.Format("select * from Hbung_CompanyInfo where CellTel='{0}'", Hbung_Phone);
                            DataTable MJStrData = DBHelpSQL.Query(MJStr).Tables[0];
                            if(MJStrData!=null&&MJStrData.Rows.Count>0)
                            {
                                  if(Zcda!=null&&Zcda.Rows.Count>0)
                                    {
                                        MJStrData.Columns.Add("CTel", typeof(string));
                                        MJStrData.Rows[0]["CTel"] = Zcda.Rows[0][0];

                                        MJStrData.Columns.Add("SID", typeof(int));
                                        MJStrData.Rows[0]["SID"] = Zcda.Rows[0][1];

                                        MJStrData.Columns.Add("SName", typeof(string));
                                        MJStrData.Rows[0]["SName"] = Zcda.Rows[0][2];

                                        MJStrData.Columns.Add("SSex", typeof(string));
                                        MJStrData.Rows[0]["SSex"] = Zcda.Rows[0][3];

                                        MJStrData.Columns.Add("SMobile", typeof(string));
                                        MJStrData.Rows[0]["SMobile"] = Zcda.Rows[0][4];

                                    }
                            }
                          
                            string Codestr=string.Format("update Hbung_ValidateCode set Status='0' where vCode='{0}' and vTel='{1}' and vType='3' ",Hbung_CodeNum,Hbung_Phone);
                            if (DBHelpSQL.ExecuteSql(Codestr) > 0)
                            {
                                string Hb_DateJson = JsonHelper.DataTableToJSON(MJStrData);
                                context.Response.Write(GenerClass.SetSucessJsData("登录成功", Hb_DateJson));
                            }
                            else
                            {
                                context.Response.Write(GenerClass.SetChangeErrorJsData("登录失败"));
                                return;
                            }
                           
                        }
                        else
                        {
                            context.Response.Write(GenerClass.SetChangeErrorJsData("登录失败"));
                            return;
                        }
                    }
                    else
                    {
                        context.Response.Write(GenerClass.SetChangeErrorJsData("与获取验证码的手机号不同"));
                        return;
                    }
                }
            }
             //请求个人资料
             if(Hbung_Meth == "2")
             {
                 string HB_InStr = string.Format("select * from Hbung_CompanyInfo where CellTel='{0}'", Hbung_Phone);
                 DataTable HB_ComInfo = DBHelpSQL.Query(HB_InStr).Tables[0];
                 if (HB_ComInfo != null && HB_ComInfo.Rows.Count > 0)
                 {
                     string comna = string.Empty;//公司名字
                     string compho = string.Empty;//公司电话
                     string comaddress = string.Empty;//公司地址
                     string comspeo = string.Empty;//服务人员
                     string ZCData = string.Format(" select CTel,SID,SName,SSex,SMobile,CAddress,CName from View_CustomerForSaleman  where RegisterMobilephone='{0}'", Hbung_Phone);
                     DataTable Zcda = DbLocalSQL.Query(ZCData).Tables[0];
                     if (Zcda != null && Zcda.Rows.Count > 0)
                     {
                         comna = Zcda.Rows[0]["CName"].ToString();
                         compho = Zcda.Rows[0]["CTel"].ToString();
                         comaddress = Zcda.Rows[0]["CAddress"].ToString();
                         comspeo = Zcda.Rows[0]["SName"].ToString();
                         string WENStr = string.Format(@"update Hbung_CompanyInfo set CompanyName='{0}',Phone='{1}',Address='{2}',ServicePerson='{3}' where CellTel='{4}' ",
                             comna, compho, comaddress, comspeo, Hbung_Phone
                             );
                         DBHelpSQL.ExecuteSql(WENStr);
                     }

                     string MJStr = string.Format("select * from Hbung_CompanyInfo where CellTel='{0}'", Hbung_Phone);
                     DataTable MJStrData = DBHelpSQL.Query(MJStr).Tables[0];
                     if (MJStrData != null && MJStrData.Rows.Count > 0)
                     {
                         if (Zcda != null && Zcda.Rows.Count > 0)
                         {
                             MJStrData.Columns.Add("CTel", typeof(string));
                             MJStrData.Rows[0]["CTel"] = Zcda.Rows[0][0];

                             MJStrData.Columns.Add("SID", typeof(int));
                             MJStrData.Rows[0]["SID"] = Zcda.Rows[0][1];

                             MJStrData.Columns.Add("SName", typeof(string));
                             MJStrData.Rows[0]["SName"] = Zcda.Rows[0][2];

                             MJStrData.Columns.Add("SSex", typeof(string));
                             MJStrData.Rows[0]["SSex"] = Zcda.Rows[0][3];

                             MJStrData.Columns.Add("SMobile", typeof(string));
                             MJStrData.Rows[0]["SMobile"] = Zcda.Rows[0][4];

                         }

                         string Hb_DateJson = JsonHelper.DataTableToJSON(MJStrData);
                         context.Response.Write(GenerClass.SetSucessJsData("登录成功", Hb_DateJson));
                         return;
                     }
                     else
                     {
                         context.Response.Write(GenerClass.SetChangeErrorJsData("用户不存在"));
                         return;
                     }
                 }
                 else
                 {
                     context.Response.Write(GenerClass.SetChangeErrorJsData("用户不存在"));
                     return;
                 }
             }
          

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}